/*
 * create on 2012-2-24
 * Copy right (2012)
 * eking All rights reserved
 */
package com.myway.components.sms.mail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPListParseEngine;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

/**
 * 类名称：FTPHelper <br/>
 * 类描述：FTP帮助类 <br/>
 * 创建时间：2015年11月5日 下午8:25:01 <br/>
 * @author 张涛
 * @version V1.0
 */
public class FTPHelper {
	private static final Logger log = Logger.getLogger(FTPHelper.class);
	
	private String userName;  // FTP 登录用户名
	private String password;  // FTP 登录密码
	private String host;      // FTP 服务器地址IP地址
	private int port;         // FTP 端口
	private FTPClient ftpClient = null; // FTP 客户端代理

	public FTPHelper(String userName, String password, String host, int port) {
		this.userName = userName;
		this.password = password;
		this.host = host;
		this.port = port;
	}

	public boolean connectServer() {
		boolean flag = true;
		if (ftpClient == null) {
			int reply;
			try {
				System.out.println("into ftpClient == null");
				ftpClient = new FTPClient();
				ftpClient.setControlEncoding("GBK"); //解决文件名乱码,默认ISO8859-1，不支持中文
				ftpClient.setDefaultPort(port);
				ftpClient.connect(host);
				ftpClient.login(userName, password);
				
				log.info("Connected to " + host);
				log.info(ftpClient.getReplyString());
				
				reply = ftpClient.getReplyCode();
				ftpClient.setDataTimeout(120000);

				if (!FTPReply.isPositiveCompletion(reply)) {
					ftpClient.disconnect();
					log.info("FTP server refused connection.");
					flag = false;
				}

			} catch (SocketException e) {
				flag = false;
				e.printStackTrace();
				log.error("登录ftp服务器 " + host + " 失败,连接超时！",e);
			} catch (IOException e) {
				flag = false;
				e.printStackTrace();
				log.error("登录ftp服务器 " + host + " 失败，FTP服务器无法打开！",e);
			}
		}
		return flag;
	}

	public void listRemoteAllFiles(String path) {
		try {
			FTPListParseEngine f = ftpClient.initiateListParsing(path);

			while (f.hasNext()) {
				FTPFile[] files = f.getNext(5);
				for (FTPFile file : files) {
					disFile(file, path);
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void disFile(FTPFile file, String path) {
		if (file.isDirectory() && !file.getName().equals(".")
				&& !file.getName().equals("..")) {
			if(log.isDebugEnabled()) {
				log.debug(File.separator + file.getName());
			}
			listRemoteAllFiles(path + File.separator + file.getName());
		} else if (!file.getName().equals(".") && !file.getName().equals("..")) {
			if(log.isDebugEnabled()) {
				log.debug(file.getName());
			}
		}
	}

	public void closeConnect() {
		log.info("关闭ftp服务器");
		try {
			if (ftpClient != null) {
				ftpClient.logout();
				ftpClient.disconnect();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void downFile(String remotePath, String fileName, String localPath) {

		FTPFile[] fs;
		try {
			ftpClient.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			log.info("download FTP File: " + fileName + "...");
			File localFile = new File(localPath + File.separator + fileName);

			FileOutputStream is = new FileOutputStream(localFile);
			ftpClient.retrieveFile(fileName, is);
			log.info("download FTP File: " + fileName + " success...");
			is.close();
		} catch (IOException e) {
			log.error("download FTP File " + fileName + " Error...",e);
		}

	}

	public void upFile(String path, String filename, String localFilePath) {
		try {
			FileInputStream in = new FileInputStream(new File(localFilePath));
			ftpClient.changeWorkingDirectory(path);
			ftpClient.storeFile(filename, in);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		FTPHelper ftp = new FTPHelper("admin", "sunwin", "192.168.5.104", 21);
		ftp.connectServer();
		//ftp.listRemoteAllFiles("/成都航空/统一支撑平台");
		ftp.downFile("/Files/", "ojdbc.jar","E:\\out");
		//ftp.upFile("/成都航空/统一支撑平台/", "ojdbc.jar", "D:/ojdbc14.jar");
		ftp.closeConnect();
	}

}